package com.xiaoma.common.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.viewbinding.ViewBinding
import com.xiaoma.common.R

/**
 * author: liangjingbo
 * date: 2022/11/23
 * describe:
 */
open class BaseDialog<VB : ViewBinding>(
    private val inflate: (LayoutInflater, ViewGroup?, Boolean) -> VB
) : DialogFragment() {

    protected val TAG = this.javaClass.simpleName
    protected val fragmentTag = TAG
    private var _binding: VB? = null
    protected val binding: VB get() = _binding!!


    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        setStyle(STYLE_NORMAL, R.style.custom_dialog)
        return CustomDialog(requireContext(), R.style.custom_dialog, ::onBackPressed).apply {
            window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            val options = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            window?.decorView?.systemUiVisibility = options
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = inflate.invoke(inflater, container, false)
        return _binding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        dialog?.let {
            generateDialog(it)
        }
        initView(view, savedInstanceState)
        initEvent()
    }

    open fun generateDialog(dialog: Dialog) {}

    open fun initEvent() {}

    open fun initView(view: View, savedInstanceState: Bundle?) {}

    open fun onBackPressed() {}

    open fun showDialog(
        fmg: FragmentManager,
        tag: String? = null
    ) {
        try {
            val t = tag ?: fragmentTag
            val restoreFragment = fmg.findFragmentByTag(t)
            Log.i(TAG, "showDialog() " +
                    "restoreFragment.isVisible: ${restoreFragment?.isVisible}")
            if (restoreFragment != null && restoreFragment.isVisible) {
                return
            }
            if (!isAdded) {
                show(fmg, t)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "showDialog() Exception: $e")
        }
    }

    fun isShow(): Boolean {
        return isAdded && isVisible
    }

    private class CustomDialog(
        context: Context,
        themeResId: Int,
        private val onBack: () -> Unit
    ) : Dialog(context, themeResId) {
        override fun onBackPressed() {
            super.onBackPressed()
            onBack.invoke()
        }
    }
}